local json = require 'cjson.safe'
local aes = require "resty.aes"
local str = require "resty.string"


local function requestAd()
    ngx.req.read_body()
    local headers = ngx.req.get_headers()
    local method = ngx.var.request_method
    local path = ngx.var.document_uri
    local query_tb = ngx.req.get_uri_args()
    ngx.log(ngx.ERR, 'test: ', json.encode(query_tb))
    local enc = query_tb['echostr']
    ngx.log(ngx.ERR, 'enc:',enc)
    local dec= ngx.decode_base64(enc)
    ngx.log(ngx.ERR, 'dec:',dec)

    local encoding_aes_key = 'yOXWbOKD9H9cBMxKTLGTLkn1csRveGAdvVVB1pfHS31' + '='
    local aes_key = ngx.decode_base64(encoding_aes_key)
    ngx.log(ngx.ERR, 'aes_key:',aes_key)
    local aes_method = assert(aes:new(aes_key, nil, aes.cipher(256, "cbc")))

    local msg = aes_method:decrypt(dec)
    ngx.log(ngx.ERR, 'msg:',msg)




    ngx.log(ngx.ERR, 'debug1111')
    local iv = "78afc8512559b62f"
    local key = "78afc8512559b62f"
    local text = "c6d1965bf800d5f7682636826c9a097e"

    local aes_128_cbc_with_iv = assert(aes:new(key, nil, aes.cipher(128, "cbc"), {iv=iv, method=nil}))
    local encrypted = ngx.encode_base64(aes_128_cbc_with_iv:encrypt(text))
    ngx.log(ngx.ERR, 'encrypted:', encrypted)

    local decrypted = aes_128_cbc_with_iv:decrypt(ngx.decode_base64(encrypted))
    ngx.log(ngx.ERR, 'decrypted:', decrypted)




    local result = {
        code = '200';
        msg = 'debug';
        info = 'test'
    }

    local body = json.encode(result)
    local code = 200

    return body, code
end

local function httpd()
    local status, result, code = pcall(
        function()
            return requestAd()
        end
    )

    if status then
        -- js script cross-domain
        ngx.header['Content-Type'] = 'application/json'
        ngx.header['Access-Control-Allow-Origin'] = '*'
        ngx.header['Access-Control-Allow-Headers'] = 'Content-Type, x-bridge-version, x-vendor-id, x-is-test'
        ngx.status = code
        ngx.say(result)
        ngx.exit(code)
    else
        ngx.log(ngx.ERR, result)
        local logstr = string.format("500 INTERNAL_SERVER_ERROR status: %s result: %s.", status, result)
        --dlog.error(logstr)
        ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
        ngx.say('500 INTERNAL_SERVER_ERROR')
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end
end

httpd()
